package vinnichenko.lab3;

/**Own packages*/
import vinnichenko.lab3.exception.*;

/**Java core packages*/
import java.io.*;

/**Java extension packages*/
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

/**Other packages*/
import org.w3c.dom.*;
import org.xml.sax.*;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

/**Class to transform XML documents from source XML docs
 * into html data using XSL templates.
 * @author Igor Vinnichenko
 * @version 1.0
 */
public class XMLTransformer{
    /**Declaration and creation logger.*/
    static Logger logger = Logger.getLogger(XMLTransformer.class);

    /**Transform XML document using provided XSLT InputStream 
     * and write resulting document to provided PrintWriter
     * @param document source document.
     * @param xslStream stream source for XSLT document.
     * @param output output stream.
     */
    public static void transform( Document document, InputStream xslStream, PrintWriter output )
        throws XSLTTransformingException{

        try{
            /**Create DOMSource for source XML document*/
            Source xmlSource = new DOMSource( document );

            /**Create StreamSource for XSLT document*/
            Source xslSource = new StreamSource( xslStream );

            /**Create StreamResult for transformation result*/
            Result result = new StreamResult( output );
         
            /**Create TransformerFactory to obtain a Transformer*/
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
         
            /**Create Transformer for performing XSL transformation*/
            Transformer transformer = transformerFactory.newTransformer( xslSource );
         
            /**Perform transformation and deliver content to client*/
            transformer.transform( xmlSource, result );
        }catch(TransformerConfigurationException confException){
            logger.error(StackWriter.getFullStackTrace( confException ));
            throw new XSLTTransformingException("Error while configuring transformer.", confException);
        }catch(TransformerFactoryConfigurationError confFactoryError){
            logger.error(StackWriter.getFullStackTrace( confFactoryError ));
            throw new XSLTTransformingException("Error while configuring transformer factory.");
        }catch ( TransformerException transformerException ){
            /**handle exception when transforming XML document*/
            logger.error(StackWriter.getFullStackTrace( transformerException ));
            throw new XSLTTransformingException("Error while transforming.", transformerException);
        }
    }
}